﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace ExcelFileQueryTool
{
    public static class ControlExtension
    {
        [DllImport("user32.dll")]
        public static extern int SendMessage(IntPtr hWnd, Int32 wMsg, bool wParam, Int32 lParam);

        private const int WM_SETREDRAW = 11;

        public static void SuspendDrawing(this Control parent)
        {
            SendMessage(parent.Handle, WM_SETREDRAW, false, 0);
        }

        public static void ResumeDrawing(this Control parent)
        {
            SendMessage(parent.Handle, WM_SETREDRAW, true, 0);
            parent.Refresh();
        }

        public static SortableBindingList<T> GetBindableListFromSource<T>(this DataGridView dgv, Func<T, bool> filter = null)
        {
            if (dgv.DataSource == null)
                return null;

            var list = dgv.DataSource as SortableBindingList<T>;

            if (list == null)
            {
                var source = dgv.DataSource as IEnumerable<T>;
                if (source == null)
                    throw new InvalidCastException("对象类型不是IEnumerable<T>，无法将数据源转换为SortableBindingList<T>。");

                list = new SortableBindingList<T>(source);
            }

            if (filter == null)
                return list;
            else
                return new SortableBindingList<T>(list.Where(filter));
        }
    }
}
